//
//  MGDateRecordsController.m
//  MoneyGoal_iOS
//
//  Created by yyb on 2023/1/10.
//  Copyright © 2023 Moneyease CO,. LTD. All rights reserved.
//

#import "MGDateRecordsController.h"
#import "MGReceiptController.h"

#import "MKDatePickerView.h"

#import "MGRecordsReceiptCell.h"
#import "MGRecordsDateCell.h"

@interface MGDateRecordsController ()
@property (nonatomic, strong) MKDatePickerView *headerView;
@property (nonatomic, strong) NSDate *date;

@property (nonatomic, strong) MGRecordModel *selectRecordModel;
@property (nonatomic, strong) NSArray *sortedReceiptModels;
// 选中的账户与类型
@property (nonatomic) NSUInteger selectCategoryUniqueId;
@property (nonatomic) NSUInteger selectAccountUniqueId;

@end

@implementation MGDateRecordsController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.date = [NSDate date];
    self.selectRecordModel = [MGRecordAccessor.shared getSelectedRecordModel];
    
    self.headerView = [[MKDatePickerView alloc] init];
    self.headerView.backgroundColor = [UIColor whiteColor];
    
    @weakify(self);
    self.headerView.dateSelectedBlock = ^(NSDate * _Nonnull date) {
        @strongify(self);
        self.date = date;
        [self refreshData];
    };
    self.headerView.dateSelectStatusBlock = ^BOOL(NSDate * _Nonnull date) {
        @strongify(self);
        NSInteger offset = [NSDate differenceWithUnit:NSCalendarUnitDay date:date toOtherDate:self.date].day;
        if (offset == 0) {
            return YES;
        }
        return NO;
    };
    self.headerView.accountTapedBlock = ^{
        @strongify(self);
        [self handleSelectAccount];
    };
    self.headerView.categoryTapedBlock = ^{
        @strongify(self);
        [self handleSelectCategory];
    };
    
    self.headerView.frame = CGRectMake(0, 0, kScreenWidth, 410 + 68);
    self.tableView.tableHeaderView = self.headerView;
}

- (void)beginQueryData {
    [super beginQueryData];
    
    [self.headerView scrollToDate:self.date];
    [self refreshData];
}

- (void)refreshData {
    self.selectRecordModel = MGRecordAccessor.shared.getSelectedRecordModel;
    
    if (self.selectRecordModel) {
        NSDate *startOfDay = self.date.startOfDay;
        NSDate *endOfDay = self.date.endOfDay;
        self.sortedReceiptModels = [self.selectRecordModel getReceiptModelsWithBeginDate:startOfDay endDate:endOfDay categoryUniqueId:self.selectCategoryUniqueId accountUniqueId:self.selectAccountUniqueId];
    }
    
    [self.headerView configViewWithAccountUniqueId:self.selectAccountUniqueId categoryUniqueId:self.selectCategoryUniqueId];
    [self.headerView.collectionView reloadData];
    [self.tableView reloadData];
}

// ====================================== 选择
// 选择账户
- (void)handleSelectAccount {
    @weakify(self);
    MGAccountModel *accountModel = [MGAccountAccessor.shared getAccountModelWithUniqueId:self.selectAccountUniqueId];

    [MGAlertView showAccountsAlertViewWithSelectModel:accountModel selectedBlock:^(MGAccountModel * _Nonnull dataModel) {
        @strongify(self);
        self.selectAccountUniqueId = dataModel.uniqueId;
        [self refreshData]; // 刷新所有数据
    } selectActionBlock:^(MGAlertViewActionType type) {
        @strongify(self);
        if (self.selectAccountUniqueId != 0) {
            self.selectAccountUniqueId = 0;
            [self refreshData];
        }
    } shouldShowAllAccounts:YES isSelectAllAccounts:self.selectAccountUniqueId == 0 hidesAllActions:YES];
}

// 选择分类
- (void)handleSelectCategory {
    @weakify(self);
    MGCategoryModel *categoryModel = [MGCategoryAccessor.shared getCategoryModelWithUniqueId:self.selectCategoryUniqueId];
    
    [MGAlertView showCategoriesAlertViewWithSelectModel:categoryModel selectedBlock:^(MGCategoryModel * _Nonnull dataModel) {
        @strongify(self);
        self.selectCategoryUniqueId = dataModel.uniqueId;
        [self refreshData]; // 刷新所有数据
    } selectActionBlock:^(MGAlertViewActionType type) {
        @strongify(self);
        if (self.selectCategoryUniqueId != 0) {
            self.selectCategoryUniqueId = 0;
            [self refreshData];
        }
    } shouldShowAllCategories:YES isSelectAllCategories:self.selectCategoryUniqueId == 0 hidesAllActions:YES];
}

- (void)handleCreateReceipt {
    if (self.selectRecordModel) {
        @weakify(self);
        [YYBViewRouter openOnClass:[MGReceiptController class] configureBlock:^(MGReceiptController *obj) {
            @strongify(self);
            obj.recordModel = self.selectRecordModel;
            
            NSDate *selectDate = self.date.startOfDay;
            selectDate = [selectDate dateByAddingHours:12];
            
            obj.selectedDate = selectDate;
            obj.updateSuccBlock = ^{
                [self refreshData];
                if (self.updateSuccBlock) {
                    self.updateSuccBlock();
                }
            };
        }];
    }
}

- (NSArray<NSString *> *)dequeueCellIdentifiers {
    return @[
        @"MGRecordsReceiptCell",
        @"MGRecordsDateCell"];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.sortedReceiptModels.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    MGReceiptModel *dataModel = self.sortedReceiptModels[indexPath.row];
    return [MGRecordsReceiptCell queryViewHeightWithDataModel:dataModel];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MGRecordsReceiptCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MGRecordsReceiptCell"];

    MGReceiptModel *dataModel = self.sortedReceiptModels[indexPath.row];
    [cell configViewWithDataModel:dataModel];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    MGReceiptModel *dataModel = self.sortedReceiptModels[indexPath.row];
    [self handleUpdateReceipt:dataModel];
}

- (void)handleUpdateReceipt:(MGReceiptModel *)dataModel {
    @weakify(self);
    [YYBViewRouter openOnClass:[MGReceiptController class] configureBlock:^(MGReceiptController *obj) {
        @strongify(self);
        obj.recordModel = self.selectRecordModel;
        obj.updateModel = dataModel;
        obj.updateSuccBlock = ^{
            [self refreshData];
            if (self.updateSuccBlock) {
                self.updateSuccBlock();
            }
        };
        obj.deleteSuccBlock = ^{
            [self refreshData];
            if (self.deleteSuccBlock) {
                self.deleteSuccBlock();
            }
        };
    }];
}

- (void)configCustomNavigationBar:(YYBNavigationBar *)navigationBar {
    [super configCustomNavigationBar:navigationBar];
    
    navigationBar.heightForBottomView = 0;
    navigationBar.shadowView.backgroundColor = APP_COLOR_MAIN_LIGHT;
    
    @weakify(self);
    YYBNavigationBarImageView *createButton = [YYBNavigationBarImageView imageViewWithConfigureBlock:^(YYBNavigationBarImageView *container, UIImageView *view) {
        view.image = [UIImage imageNamed:@"date_add_receipt"];
        container.contentSize = CGSizeMake(20, 44);
        container.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 15);
    } tapedActionBlock:^(YYBNavigationBarContainer *container) {
        @strongify(self);
        [self handleCreateReceipt];
    }];
    
    navigationBar.rightBarContainers = @[createButton];
}

- (NSString *)customPageTitle {
    return @"收支详情";
}

@end
